# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from . import app
from com.zzh.dao_v2.historyDao import HistoryDao
from com.zzh.dao_v2.itemDao import ItemDao
from com.zzh.dao_v2.viewItemDao import ViewItemDao
from com.zzh.dao_v2.viewAllItemsDao import ViewAllItemsDao
CORS(app, supports_credentials=True)

@app.route('/findViewItem', methods=['GET'])
def find_view_item():
    """
    查询 view_area
    :return:
    """
    try:
        ItemDao().updateItemStates()
    except Exception, e:
        return jsonify({"code": 0, "message": str(e)})

    info = ViewItemDao().findInfo()


    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"info": [], "message": {"code": 0, "status": "error"}})

@app.route('/findViewItemByCondition', methods=['POST'])
def find_view_item_by_condition():
    if not request.json:
        abort(400)

    try:
        ItemDao().updateItemStates()
    except Exception, e:
        return jsonify({"code": 0, "message": str(e)})

    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})

    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})

    try:
        queryType=request.json['overdue']
        if queryType==0:
            info, total = ViewItemDao().find_by_conditionOverDue0(pageIndex=pageIndex, pageSize=pageSize, conditions=conditions,
                                                          multiSort=multiSort)
            if info == -200:
                return jsonify({"info": [], "message": {"code": -200, "status": "sql error!"}})
            elif info:
                return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
            else:
                return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
        elif queryType==1:
            info, total = ViewItemDao().find_by_conditionOverDue1(pageIndex=pageIndex, pageSize=pageSize, conditions=conditions,
                                                          multiSort=multiSort)
            if info == -200:
                return jsonify({"info": [], "message": {"code": -200, "status": "sql error!"}})
            elif info:
                return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
            else:
                return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
        else:
                return jsonify({"info": [], "message": {"code": 0, "status": "Status Error"}})
    except:
        info, total = ViewItemDao().find_by_condition(pageIndex=pageIndex, pageSize=pageSize, conditions=conditions,
                                                      multiSort=multiSort)
        if info == -200:
            return jsonify({"info": [], "message": {"code": -200, "status": "sql error!"}})
        elif info:
            return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
        else:
            return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})



@app.route('/findItemByRandom', methods=['POST'])
def findItemByRandom():
    if not request.json:
        abort(400)
    top = request.json.get('top', 1)
    if not isinstance(top, int):
        return jsonify({"message": {"code": 0, "status": "参数类型错误!!!"}})

    rsData = ViewItemDao().getRandomItem(top)

    if rsData:
        return jsonify({"info": rsData, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})

@app.route('/findItemBySearch', methods=['POST'])
def findItemBySearch():
    if not request.json:
        abort(400)

    try:
        ItemDao().updateItemStates()
    except Exception, e:
        return jsonify({"code": 0, "message": str(e)})
    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})
    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})
    try:
        keyword = request.json['keyword']
    except:
        return jsonify({"message": {"code": 0, "status": "缺少必要参数"}})



    hisType=request.json.get('queryType')
    userId=request.json.get('userId')

    if userId:

        check=[]
        for ch in keyword.decode('utf-8'):
            if u'\u4e00' <= ch <= u'\u9fff':
                pass
            else:
                check.append(ch)

        if len(check)==0:
            if hisType==0:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)

                result, count=ViewAllItemsDao().itemBigSearchAndCondition0(keyword=keyword,pageIndex=pageIndex,pageSize=pageSize,conditions=conditions,multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==1:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)

                result, count = ViewAllItemsDao().itemBigSearchAndCondition1(keyword=keyword, pageIndex=pageIndex,pageSize=pageSize, conditions=conditions,multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==2:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)
                result, count = ViewAllItemsDao().itemBigSearchAndCondition2(keyword=keyword, pageIndex=pageIndex,
                                                                           pageSize=pageSize, conditions=conditions,
                                                                           multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==3:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)
                result, count = ViewAllItemsDao().itemBigSearchAndCondition3(keyword=keyword, pageIndex=pageIndex,
                                                                           pageSize=pageSize, conditions=conditions,
                                                                           multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==4:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition4(keyword=keyword, pageIndex=pageIndex,
                                                                           pageSize=pageSize, conditions=conditions,
                                                                           multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            else:
                return jsonify({"message": {"code": 0, "status": "hisType Error!"}})

        else:
            if hisType==0:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)

                result, count = ViewAllItemsDao().itemBigSearchAndCondition5(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==1:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)

                result, count = ViewAllItemsDao().itemBigSearchAndCondition1(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==2:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)
                result, count = ViewAllItemsDao().itemBigSearchAndCondition2(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==3:
                res = HistoryDao().t1(userId, hisType, keyword)
                if res == 0:
                    info = {
                        'userId': userId,
                        'userIp': request.remote_addr,
                        'hisKeywords': keyword,
                        'hisType': hisType,
                        'hisSearchCount': 1
                    }
                    HistoryDao().insertHis(info)
                else:
                    hisId = res[0]
                    hisCount = res[1]
                    HistoryDao().updateHiCount(hisId, hisCount)
                result, count = ViewAllItemsDao().itemBigSearchAndCondition3(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType==4:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition6(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            else:
                return jsonify({"message": {"code": 0, "status": "hisType Error!"}})
    else:
        check = []
        for ch in keyword.decode('utf-8'):
            if u'\u4e00' <= ch <= u'\u9fff':
                pass
            else:
                check.append(ch)

        if len(check) == 0:
            if hisType == 0:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition0(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 1:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition1(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 2:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition2(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 3:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition3(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 4:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition4(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            else:
                return jsonify({"message": {"code": 0, "status": "hisType Error!"}})

        else:
            if hisType == 0:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition5(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 1:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition1(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 2:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition2(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 3:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition3(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            elif hisType == 4:
                result, count = ViewAllItemsDao().itemBigSearchAndCondition6(keyword=keyword, pageIndex=pageIndex,
                                                                             pageSize=pageSize, conditions=conditions,
                                                                             multiSort=multiSort)
                if result == -200:
                    return jsonify({"message": {"code": 0, "status": "Database Exception: -200"}})
                elif result:
                    return jsonify({"total": count, "info": result, "message": {"code": 1, "status": "success"}})
                else:
                    return jsonify({"message": {"code": 0, "status": "No such data!"}})

            else:
                return jsonify({"message": {"code": 0, "status": "hisType Error!"}})